package com.charles.seckillAuth.service;

import com.charles.seckillapi.feignService.RemoteUserService;
import com.charles.seckillapi.model.UserLogin;
import com.charles.seckillcommon.core.constants.RoleConstants;
import com.charles.seckillcommon.core.domain.R;
import com.charles.seckillcommon.core.exceptions.ServiceException;
import com.charles.seckillcommon.core.utils.BcryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Charles-H
 * 
 * 登录业务
 */
@Component
public class SysLoginService {
    
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 秒杀产品界面登录
     * @param userCard
     * @param password
     * @return
     */
    public UserLogin login(String userCard, String password) {
        if (userCard.isEmpty() || password.isEmpty()) {
            throw new ServiceException("身份证号码或密码为空");
        }
        
        /**
         * 调用客户服务，获取客户信息
         */
        R<UserLogin> userResult = remoteUserService.queryUserInfoByUserCard(userCard, RoleConstants.INNER);
        
        if (R.FAIL.equals(userResult.getCode())) {
            throw new ServiceException(userResult.getMsg());
        }

        UserLogin userLogin = userResult.getData();
        
        if (!BcryptUtil.verifyPassword(password, userLogin.getSysUser().getPassword())) {
            throw new ServiceException("身份证号码或密码错误");
        }
        
        return userLogin;
    }

    /**
     * 后台管理系统登录
     * @param userCard
     * @param password
     * @return
     */
    public UserLogin loginAdmin(String userCard, String password) {
        if (userCard.isEmpty() || password.isEmpty()) {
            throw new ServiceException("身份证号码或密码为空");
        }

        /**
         * 调用客户服务，获取客户信息
         */
        R<UserLogin> userResult = remoteUserService.queryUserInfoByUserCard(userCard, RoleConstants.INNER);

        if (R.FAIL.equals(userResult.getCode())) {
            throw new ServiceException(userResult.getMsg());
        }

        UserLogin userLogin = userResult.getData();
        
        if (userLogin.getSysUser().getRole_id() != 1) {
            throw new ServiceException("您不是管理员，无权访问");
        }

        if (!BcryptUtil.verifyPassword(password, userLogin.getSysUser().getPassword())) {
            throw new ServiceException("身份证号码或密码错误");
        }

        return userLogin;
    }

}
